using System;
using System.Data;
using System.Windows.Forms;
using MySqlConnector;

namespace Front._1124;

public partial class BookMain : Form
{
    public BookMain()
    {
        InitializeComponent();
        button2.Click += buttonAdd_Click; // 新增按钮事件
        AddDeleteButton(); // 添加删除按钮
        this.Load += BookMain_Load; // 窗体加载事件
        button1.Click += button1_Click; // 查询按钮事件
    }

    private void BookMain_Load(object sender, EventArgs e)
    {
        GetAllBooks(); // 加载图书列表
        GetAllCategories(); // 加载分类（从book_info提取）
    }

    // 加载所有图书（适配book_info表结构）
    private void GetAllBooks()
    {
        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            // 查询book_info表所有字段（适配你的表结构）
            string sql = "SELECT book_id, isbn, book_name, author, publisher_id, publish_date, " +
                         "book_category, book_price, book_pages, book_status, shelf_id FROM book_info";
            MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet, "book_info");

            dataGridView1.DataSource = dataSet.Tables["book_info"];
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }
        catch (Exception ex)
        {
            MessageBox.Show($"加载图书失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    // 从book_info表提取所有不重复的分类（适配你的表结构，无book_category表）
    private void GetAllCategories()
    {
        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            // 提取不重复的book_category值作为分类选项
            string sql = "SELECT DISTINCT book_category FROM book_info ORDER BY book_category";
            using var command = new MySqlCommand(sql, connection);
            using var reader = command.ExecuteReader();

            comboBox2.Items.Add("全部"); // 添加"全部"选项

            while (reader.Read())
            {
                comboBox2.Items.Add(reader.GetString("book_category"));
            }

            comboBox2.SelectedIndex = 0; // 默认选中"全部"
        }
        catch (Exception ex)
        {
            MessageBox.Show($"加载分类失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    // 创建删除按钮
    private void AddDeleteButton()
    {
        Button deleteBtn = new Button();
        deleteBtn.Text = "删除选中";
        deleteBtn.Location = new System.Drawing.Point(1007, 32);
        deleteBtn.Size = new System.Drawing.Size(90, 30);
        deleteBtn.ForeColor = System.Drawing.Color.Red;
        deleteBtn.Click += buttonDelete_Click;
        this.Controls.Add(deleteBtn);
    }

    // 新增按钮：打开新增表单
    private void buttonAdd_Click(object sender, EventArgs e)
    {
        AddBookForm addForm = new AddBookForm();
        if (addForm.ShowDialog() == DialogResult.OK)
        {
            GetAllBooks(); // 刷新列表
        }
    }

    // 删除选中图书（适配book_id主键）
    private void buttonDelete_Click(object sender, EventArgs e)
    {
        if (dataGridView1.SelectedRows.Count == 0)
        {
            MessageBox.Show("请先选中要删除的图书行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        if (MessageBox.Show("确定删除选中图书？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
            return;

        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                if (row.Cells["book_id"].Value != null && int.TryParse(row.Cells["book_id"].Value.ToString(), out int bookId))
                {
                    string sql = "DELETE FROM book_info WHERE book_id = @bookId";
                    using var command = new MySqlCommand(sql, connection);
                    command.Parameters.AddWithValue("@bookId", bookId);
                    command.ExecuteNonQuery();
                }
            }

            MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            GetAllBooks();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    // 查询按钮（按名称和分类筛选）
    private void button1_Click(object sender, EventArgs e)
    {
        string bookName = textBox1.Text.Trim();
        string category = comboBox2.SelectedItem.ToString();

        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            string sql = "SELECT book_id, isbn, book_name, author, publisher_id, publish_date, " +
                         "book_category, book_price, book_pages, book_status, shelf_id FROM book_info WHERE 1=1";
            if (!string.IsNullOrEmpty(bookName))
                sql += " AND book_name LIKE @bookName";
            if (category != "全部")
                sql += " AND book_category = @category";

            using var command = new MySqlCommand(sql, connection);
            if (!string.IsNullOrEmpty(bookName))
                command.Parameters.AddWithValue("@bookName", $"%{bookName}%");
            if (category != "全部")
                command.Parameters.AddWithValue("@category", category);

            MySqlDataAdapter adapter = new MySqlDataAdapter(command);
            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet, "book_info");
            dataGridView1.DataSource = dataSet.Tables["book_info"];
        }
        catch (Exception ex)
        {
            MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}